import { db } from '../database/db';
import { SysRoleMenu } from '../domain/sys_role_menu';

export async function getRoleMenus(role_id: number) {
    return await db.selectFrom('sys_role_menu')
        .select(['menu_id'])
        .where('role_id', '=', role_id)
        .execute();
}

export async function createRoleMenus(role_id: number, menu_ids: number[]) {
    if (menu_ids.length === 0) return 0;
    
    const values = menu_ids.map(menu_id => ({
        role_id,
        menu_id
    }));
    
    const result = await db.insertInto('sys_role_menu')
        .values(values)
        .executeTakeFirst();
    
    return Number((result as any).insertId);
}

export async function deleteRoleMenus(role_id: number) {
    const result = await db.deleteFrom('sys_role_menu')
        .where('role_id', '=', role_id)
        .executeTakeFirst();
    
    return Number((result as any).numDeletedRows);
}

export async function updateRoleMenus(role_id: number, menu_ids: number[]) {
    // 先删除原有的关联
    await deleteRoleMenus(role_id);
    
    // 再创建新的关联
    if (menu_ids.length > 0) {
        return await createRoleMenus(role_id, menu_ids);
    }
    
    return 0;
} 